using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace Avinor.NET
{
    public class AvinorFlightParser: AvinorParser
    {
        public AvinorFlightParser(Stream stream) : base(stream) {}


        public IEnumerable<Flight> GetFlights()
        {
            var flights = from flight in GetDescendants("flight")
                select new Flight
                   {
                       Airline = flight.Element("airline").Value,
                       FlightId = flight.Element("flight_id").Value,
                       LastLeg = ParseLastLeg(flight.Element("dom_int").Value),
                       ScheduledTime = DateTime.Parse(flight.Element("schedule_time").Value),
                       Direction = ParseDirection(flight.Element("arr_dep").Value),
                       Airport = flight.Element("airport").Value,
                       Belt = flight.Element("belt") == null ? (int?)null : int.Parse(flight.Element("belt").Value),
                       Gate = flight.Element("gate") == null ? null : flight.Element("gate").Value
                   };
            return flights;

        }

        private FlightDirection ParseDirection(string value)
        {
            switch (value.ToUpper())
            {
                case "A":
                    return FlightDirection.Arrival;
                case "D":
                    return FlightDirection.Departure;
            }
            throw new ArgumentOutOfRangeException("arr_dep", "Expected A or D");
        }

        private FlightArea ParseLastLeg(string value)
        {
            switch (value.ToUpper())
            {
                case "D":
                    return FlightArea.Domestic;
                case "I":
                    return FlightArea.International;
                case "S":
                    return FlightArea.Schengen;
            }
            throw new ArgumentOutOfRangeException("dom_int", "Expected D, I or S, got '");
        }
    }
}